package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.DatePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.dms.Product
import com.cheyun.netsalev3.bean.home.HomeReportInfo
import com.cheyun.netsalev3.bean.home.HomeTaskInfo
import com.cheyun.netsalev3.bean.home.HomeTopInfo
import com.cheyun.netsalev3.repository.ChooseCarRepository
import com.cheyun.netsalev3.repository.HomeTaskFragment2Repository
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.view.*
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyun.netsalev3.view.drivelist.DriveListActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.PopDialog
import java.text.SimpleDateFormat
import java.util.*
import com.jeremyliao.liveeventbus.LiveEventBus

class HomeTaskFragment2ViewModel(var homeTaskFragment2Repository: HomeTaskFragment2Repository) : ViewModel(), PopDialog.PopDialogListener {

    var data = ObservableField<PersonlistParam>()
    var showMessage = ObservableField<String>("")
    var showMum = ObservableField<Int>(0)
    var isShow= ObservableField<Boolean>(false)
    var isHuafeiTipShow = ObservableField<Boolean>(false)
    var isHuafeiTipShow2 = MutableLiveData<Boolean>()
    var huafeiMsg = ObservableField<String>("")
    var firstMessageType = "";

    var hasMessageCallback = false
    var currentDaodian = 0
    var currentLianxi = 0

    var currentPos = 0

    var chooseCarRepository: ChooseCarRepository = ChooseCarRepository();

    //选择的时间
    var startTime = ObservableField<String>("")
    //选择的车系
    var seriesName = ObservableField<String>("总车系")
    var series = MutableLiveData<List<NameIdParam>>()
    var seriesId = "0"
    private var dialog: PopDialog? = null

    var backgrounds = arrayListOf<Int>()
    var icons = arrayListOf<Int>()

    var reportDatas = MutableLiveData<List<HomeReportInfo>>()

    var taskInfo = ObservableField<HomeTopInfo>()

    //数据初始化
    var dataList = arrayListOf(
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData(),
            MutableLiveData<PersonlistParam>()
    )
    var calendarList = MutableLiveData<List<Calendar>>()

    init {
        var dateFormat = SimpleDateFormat("yyyy-MM-dd")
        val c = Calendar.getInstance()
        var date = dateFormat.format(c.timeInMillis)
        startTime.set(date)

        icons.add(R.drawable.xianxiaxiansuo)
        icons.add(R.drawable.xinzengpaichen)
        icons.add(R.drawable.shijialiang)
        icons.add(R.drawable.jingsuodan)
        icons.add(R.drawable.genjinliang)
        icons.add(R.drawable.chengjiaoliang)

        backgrounds.add(R.drawable.rectangle_6dp_chengse)
        backgrounds.add(R.drawable.rectangle_6dp_zise)
        backgrounds.add(R.drawable.rectangle_6dp_tianlanse)
        backgrounds.add(R.drawable.rectangle_6dp_danlvse)
        backgrounds.add(R.drawable.rectangle_6dp_chengse)
        backgrounds.add(R.drawable.rectangle_6dp_zise)
        initData()
    }

//    var networkState = Transformations.switchMap(dataList[7]) { homeTaskFragment2Repository.networkState }!!

    var networkState = Transformations.switchMap(dataList[0]) {
        homeTaskFragment2Repository.networkState
    }!!

    fun refresh() {
        initData()
        loadData(0)
    }

    /**
     * 消息回调
     */
    fun getMessageCallBack(item: NoticeData) {
        var lists = item.rows
        if (lists.isNotEmpty()) {
            if(item.unread>0) {
                showMessage.set(lists[0].message)
                firstMessageType = lists[0].ckey;
            }else{
                showMessage.set("暂无新消息")
            }
            isShow.set(true)
        } else {
            showMessage.set("暂无新消息")
            isShow.set(false)
        }
        hasMessageCallback = true
        showMum.set(item.unread)
    }

    /**
     * 消息列表
     */
    fun onClickMessage(view: View) {
        view.context.startActivity(Intent(view.context, MessageListActivity::class.java))
    }
    fun onClickTop(view:View,type:Int){
        if(type == 1){
            //工单列表
            ToastUtil.showToast("更新中...")
        }else if(type == 2){
            //预约单
            view.context.startActivity(Intent(view.context, DriveListActivity::class.java))
        }else if(type == 3){
            //重点客户
            ToastUtil.showToast("更新中...")
        }else if(type == 4){
            //素材库
            ToastUtil.showToast("更新中...")
        }
    }

    fun onClickSearchClue(view:View){
        var intent = Intent(view.context, SearchActivity::class.java)
        intent.putExtra("nkey", "archive.index")
        view.context.startActivity(intent)
    }

    fun onClickTask(view:View,ckey:String){
        var intent = Intent(view.context, TaskListActivity::class.java)
        intent.putExtra("ckey",ckey)
        view.context.startActivity(intent)
    }

    fun onClickScan(view: View){
        LiveEventBus.get().with("scan").postValue("")
//        val intent = Intent(view.context, ScanCodeActivity::class)
//        intent.putExtra("model", ScanStyle.WECHAT)
//        mActivity.startActivityForResult(intent, QUESTCODE)
//
//
//        view.context.startActivity(Intent(view.context, ScanCodeActivity::class.java))

//        ScanCodeConfig.create(this@MainActivity, mFragment)
//                //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式    ScanStyle.CUSTOMIZE ： 自定义样式
//                .setStyle(style)
//                //扫码成功是否播放音效  true ： 播放   false ： 不播放
//                .setPlayAudio(false)
//                .buidler()
//                //跳转扫码页   扫码页可自定义样式
//                .start(ScanCodeActivity::class.java)
    }

    private fun initData() {
//        var dateFormat = SimpleDateFormat("yyyy-MM-dd")
//        var temcalendar = ArrayList<Calendar>()
//        for (i in 0..7) {
//            val c = Calendar.getInstance()
//            c.add(Calendar.DAY_OF_MONTH, i)
//            var date = dateFormat.format(c.timeInMillis)
//            temcalendar.add(c)
//
//            dataList[i].postValue(null)
//        }
//        calendarList.postValue(temcalendar)
        homeTaskFragment2Repository.GetMessage(this::getMessageCallBack)
//        homeTaskFragment2Repository.getMoney(this::moneyCall)
        getBlist()
    }
    fun getBlist(){
        homeTaskFragment2Repository.getBlist(startTime.get()!!,seriesId, this::blistCall)
    }

    fun loadData(pos:Int){
        Log.i("loaddata",pos.toString())
        var dateFormat = SimpleDateFormat("yyyy-MM-dd")
        val c = Calendar.getInstance()
        c.add(Calendar.DAY_OF_MONTH, pos)
        var date = dateFormat.format(c.timeInMillis)
        if(dataList.get(pos).value == null) {
            var method: (p: PersonlistParam) -> Unit = {
                it.setTimData()
                data.set(it)
                it.calendar = c
                dataList[pos].postValue(it)
            }
            homeTaskFragment2Repository.getData(date, method)
        }else{
            dataList[pos].value?.apply {
                this.setTimData()
                data.set(this)
            }
        }

        currentPos = pos
    }

    fun onCloseHuafeiTip(view:View){
        isHuafeiTipShow.set(false)
        isHuafeiTipShow2.postValue(false)
    }

    fun onclickItem(view: View, item: ConnectData) {
        //跳接待
        if (item.follow_type == "invite") {
            var intent = Intent(view.context, ReceptionActivity::class.java)
            intent.putExtra("id", item.id)
            view.context.startActivity(intent)
        } else {
            //跳详情
            var intent = Intent(view.context, DefeatDetailsActivity::class.java)
            intent.putExtra("tid", item.tid)
            intent.putExtra("nkey", "archive.index")
            view.context.startActivity(intent)
        }
    }

    fun refreshMessage() {
        homeTaskFragment2Repository.GetMessage(this::getMessageCallBack)
    }

    fun getMoney() {
//        homeTaskFragment2Repository.getMoney (this::moneyCall)
    }

    fun moneyCall(data: MoneyParam) {
        if(data!=null){
            if(!data.alert.isNullOrEmpty()){
                isHuafeiTipShow.set(true)
                isHuafeiTipShow2.postValue(true)
                huafeiMsg.set(data.alert)
            }
        }
    }

    fun blistCall(data: HomeTaskInfo) {
        if(data!=null){
            for (i in 0 until data?.data.size) {
//                data?.data.get(i).background = (i%6).toString()
                data?.data.get(i).background = backgrounds.get(i%6)
                data?.data.get(i).icon = icons.get(i%6)
            }
            reportDatas.postValue(data.data)

            taskInfo.set(data.task)
        }
    }

    fun clickRecordTable(view: View) {
        var intent = Intent(view.context, H5Activity::class.java)
        intent.putExtra("url", MySharedPreferences.getLoginData()?.recordTable)
        view.context.startActivity(intent)
    }

    fun onChooseDateType(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSetstart
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }
    fun onChooseSeries(view:View){
        var content = view.context
        if (content is AppCompatActivity) {
            chooseCarRepository.getDMSseries("1", "", this@HomeTaskFragment2ViewModel::setChex)
        }
        if (content is AppCompatActivity) {
            if (dialog == null) {
                dialog = PopDialog()
                dialog!!.listener = this
            }
            dialog?.show(content.supportFragmentManager, "pop")
        }
    }

    /**
     * 选择时间回调
     */
    fun onDateSetstart(view: DatePicker, year: Int, month: Int, day: Int) {
        startTime.set("$year-$month-$day")
        getBlist()
    }

    fun setChex(type:String,list: List<Product>) {
        when (type) {
            "1" -> {
                var ls = arrayListOf<NameIdParam>()
                list.forEach { ls.add(NameIdParam(it.title,it.id.toString())) }
                series.postValue(ls)
            }
        }
    }

    override var list: MutableLiveData<List<NameIdParam>>
        get(){
            return series
        }
        set(value) { list = value}
    override var dialogType: MutableLiveData<String>
        get() {
            return MutableLiveData("list")
        }
        set(value) {dialogType = value}
    override var dialogTitle: MutableLiveData<String>
        get() {
            return MutableLiveData("选择车系")
        }
        set(value) {
            dialogTitle = value
        }

    override fun onClickItem(view: View, param: NameIdParam) {
        series.value?.apply {
            for (item in this) {
                item.IsSelect = param.id.equals(item.id)
            }
        }
        seriesName.set(param.name)
        seriesId = param.id.toString()
        if(dialog!=null){
            dialog?.dismiss()
        }
        getBlist()
    }

    override fun onDialogSubmit(view: View, param: String) {

    }

}